package com.mingtu.guards.view;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.FilteClassAdapter;
import com.mingtu.guards.adapter.FilteGenusAdapter;
import com.mingtu.guards.adapter.FilteKmAdapter;
import com.mingtu.guards.adapter.FilteLevelAdapter;
import com.mingtu.guards.bean.AmimalFilteBean;
import com.mingtu.guards.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @ClassName :
 * @Author : wkk
 * @Date : 2023-10-7 14:52:03
 * @Email : 1281573890@qq.com
 * @Eescription :
 */
public class FilterAnimalView extends FrameLayout {

    @BindView(R.id.tv_fold_class)
    TextView tvFoldClass;
    @BindView(R.id.layout_arrow_class)
    LinearLayout layoutArrowClass;
    @BindView(R.id.layout_class)
    RelativeLayout layoutClass;
    @BindView(R.id.recycler_class)
    RecyclerView recyclerClass;
    @BindView(R.id.tv_fold_level)
    TextView tvFoldLevel;
    @BindView(R.id.layout_arrow_level)
    LinearLayout layoutArrowLevel;
    @BindView(R.id.layout_level)
    RelativeLayout layoutLevel;
    @BindView(R.id.recycler_level)
    RecyclerView recyclerLevel;
    @BindView(R.id.tv_fold_km)
    TextView tvFoldKm;
    @BindView(R.id.layout_arrow_km)
    LinearLayout layoutArrowKm;
    @BindView(R.id.layout_km)
    RelativeLayout layoutKm;
    @BindView(R.id.recycler_km)
    RecyclerView recyclerKm;
    @BindView(R.id.tv_fold_genus)
    TextView tvFoldGenus;
    @BindView(R.id.layout_arrow_genus)
    LinearLayout layoutArrowGenus;
    @BindView(R.id.layout_genus)
    RelativeLayout layoutGenus;
    @BindView(R.id.recycler_genus)
    RecyclerView recyclerGenus;
    @BindView(R.id.layout_right_drawer)
    RelativeLayout layoutRightDrawer;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    @BindView(R.id.filter_cancle_view)
    FilterCancleView filterCancleView;
    @BindView(R.id.filter_sure_view)
    FilterSureView filterSureView;
    private View view;
    private Activity activity;
    private Unbinder unbinder;
    private static final String[] classText = {"动物", "植物"};
    private String kmName;
    private String classType = "0";
    private String levelName;
    private String genusName;
    private List<String> kmList = new ArrayList<>();
    private List<String> levelList = new ArrayList<>();
    private List<String> genusList = new ArrayList<>();
    private List<String> myKmList;
    private List<String> myGenusList;
    private FilteLevelAdapter filteLevelAdapter;
    private FilteKmAdapter filteKmAdapter;
    private FilteGenusAdapter filteGenusAdapter;
    private boolean kmFlag = false; //记录科目是否展开
    private boolean genusFlag = false; //记录属性是否展开
    private OnClickListener onClickListener = null;
    private FilteClassAdapter filteClassAdapter;

    public FilterAnimalView(Context context) {
        this(context, (AttributeSet) null, 0);
    }

    public FilterAnimalView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FilterAnimalView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        view = LayoutInflater.from(context).inflate(R.layout.layout_filter_animal, this, true);
        this.activity = (Activity) context;
        unbinder = ButterKnife.bind(this, view);
        init();
    }

    private void init() {
        //物种类别 (默认选择 动物)
        FlexboxLayoutManager flm1 = new FlexboxLayoutManager(activity);
        flm1.setFlexWrap(FlexWrap.WRAP);
        flm1.setFlexDirection(FlexDirection.ROW);
        flm1.setAlignItems(AlignItems.STRETCH);
        flm1.setJustifyContent(JustifyContent.FLEX_START);
        recyclerClass.setLayoutManager(flm1);

        List<String> classList = new ArrayList<>();
        for (int i = 0; i < classText.length; i++) {
            classList.add(classText[i]);
        }

        filteClassAdapter = new FilteClassAdapter(activity, classList);
        recyclerClass.setAdapter(filteClassAdapter);
        filteClassAdapter.setOnItemClickListener(new FilteClassAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //初始值为null,获取全部,点击筛选，选择单个保护站下的摄像头
                classType = position + "";
                filteClassAdapter.upData(position);

                //重新获取 科目、属性
                getKM();
                getGenus();
                getLevel();
            }
        });


        //保护级别
        FlexboxLayoutManager flm2 = new FlexboxLayoutManager(activity);
        flm2.setFlexWrap(FlexWrap.WRAP);
        flm2.setFlexDirection(FlexDirection.ROW);
        flm2.setAlignItems(AlignItems.STRETCH);
        flm2.setJustifyContent(JustifyContent.FLEX_START);
        recyclerLevel.setLayoutManager(flm2);

        filteLevelAdapter = new FilteLevelAdapter(activity, levelList);
        recyclerLevel.setAdapter(filteLevelAdapter);

        //科目
        FlexboxLayoutManager flm3 = new FlexboxLayoutManager(activity);
        flm3.setFlexWrap(FlexWrap.WRAP);
        flm3.setFlexDirection(FlexDirection.ROW);
        flm3.setAlignItems(AlignItems.STRETCH);
        flm3.setJustifyContent(JustifyContent.FLEX_START);
        recyclerKm.setLayoutManager(flm3);

        filteKmAdapter = new FilteKmAdapter(activity, kmList);
        recyclerKm.setAdapter(filteKmAdapter);


        //属性
        FlexboxLayoutManager flm4 = new FlexboxLayoutManager(activity);
        flm4.setFlexWrap(FlexWrap.WRAP);
        flm4.setFlexDirection(FlexDirection.ROW);
        flm4.setAlignItems(AlignItems.STRETCH);
        flm4.setJustifyContent(JustifyContent.FLEX_START);
        recyclerGenus.setLayoutManager(flm4);

        filteGenusAdapter = new FilteGenusAdapter(activity, genusList);
        recyclerGenus.setAdapter(filteGenusAdapter);

        filterCancleView.setOnClickListener(new FilterCancleView.OnClickListener() {
            @Override
            public void onClickCancel() {
                if (onClickListener != null)
                    onClickListener.onClickCancel();
            }
        });

        filterSureView.setOnClickListener(new FilterSureView.OnClickListener() {
            @Override
            public void onClickReset() {
                resetFiltAdapteData();
                if (onClickListener != null)
                    onClickListener.onClickReset(kmName, classType, levelName, genusName);
            }

            @Override
            public void onClickSure() {
                if (onClickListener != null)
                    onClickListener.onClickSure(kmName, classType, levelName, genusName);
            }
        });

        getLevel();
        getKM();
        getGenus();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        unbinder.unbind();
    }


    @OnClick({R.id.layout_arrow_km, R.id.layout_arrow_genus})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_arrow_km:
                if (kmFlag) { //默认为false,收起状态
                    kmFlag = false;
                    tvFoldKm.setText("展开");
                    filteKmAdapter.upData(myKmList);
                } else {
                    kmFlag = true;
                    tvFoldKm.setText("收起");
                    filteKmAdapter.upData(kmList);
                }

                break;

            case R.id.layout_arrow_genus:
                if (genusFlag) { //默认为false,收起状态
                    genusFlag = false;
                    tvFoldGenus.setText("展开");
                    filteGenusAdapter.upData(myGenusList);
                } else {
                    genusFlag = true;
                    tvFoldGenus.setText("收起");
                    filteGenusAdapter.upData(genusList);
                }

                break;
        }
    }

    /**
     * 保护级别
     */
    private void getLevel() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("type", 0);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_RES_FILTE_LEVE + "/0")
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(activity) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            AmimalFilteBean amimalFilteBean = new AmimalFilteBean();
                            amimalFilteBean = gson.fromJson(result, AmimalFilteBean.class);
                            List<String> levelList = amimalFilteBean.getList();
                            if (levelList != null) {
                                if (levelList.size() > 0) {
                                    filteLevelAdapter.upData(levelList);
                                    filteLevelAdapter.setOnItemClickListener(new FilteLevelAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(View view, int position) {
                                            boolean isChecked = filteLevelAdapter.upData(position);
                                            if (isChecked) {
                                                levelName = levelList.get(position);
                                            } else {
                                                levelName = null;
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 科目
     */
    private void getKM() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("type", Integer.parseInt(classType));
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_RES_FILTE_KM + "/" + classType)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(activity) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            AmimalFilteBean amimalFilteBean = new AmimalFilteBean();
                            amimalFilteBean = gson.fromJson(result, AmimalFilteBean.class);
                            kmList = amimalFilteBean.getList();
                            if (kmList != null) {
                                int size = kmList.size();
                                if (size > 0) {
                                    if (size > 6) {
                                        //数据大于6的时候，取前6条数据，有展开收回操作
                                        myKmList = kmList.subList(0, 6);
                                        filteKmAdapter.upData(myKmList);
                                        layoutArrowKm.setVisibility(View.VISIBLE);
                                    } else {
                                        //数据个数小与6的时候，展开视图隐藏
                                        filteKmAdapter.upData(kmList);
                                        layoutArrowKm.setVisibility(View.GONE);
                                    }
                                    kmFlag = false;
                                    tvFoldKm.setText("展开");
                                    filteKmAdapter.setOnItemClickListener(new FilteKmAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(View view, int position) {
                                            //初始值为null,获取全部,点击筛选，选择单个保护站下的摄像头
                                            boolean isChecked = filteKmAdapter.upData(position);
                                            if (isChecked) {
                                                kmName = kmList.get(position);
                                            } else {
                                                kmName = null;
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 属性
     */
    private void getGenus() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("type", Integer.parseInt(classType));
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_RES_FILTE_GENUS + "/" + classType)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(activity) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            AmimalFilteBean amimalFilteBean = new AmimalFilteBean();
                            amimalFilteBean = gson.fromJson(result, AmimalFilteBean.class);
                            genusList = amimalFilteBean.getList();
                            if (genusList != null) {
                                int size = genusList.size();
                                if (size > 0) {
                                    if (size > 6) {
                                        //数据大于6的时候，取前6条数据，有展开收回操作
                                        myGenusList = genusList.subList(0, 6);
                                        filteGenusAdapter.upData(myGenusList);
                                        layoutArrowGenus.setVisibility(View.VISIBLE);
                                    } else {
                                        //数据个数小与6的时候，展开视图隐藏
                                        filteGenusAdapter.upData(genusList);
                                        layoutArrowGenus.setVisibility(View.GONE);
                                    }
                                    genusFlag = false;
                                    tvFoldGenus.setText("展开");
                                    filteGenusAdapter.setOnItemClickListener(new FilteGenusAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(View view, int position) {
                                            boolean isChecked = filteGenusAdapter.upData(position);
                                            if (isChecked) {
                                                genusName = genusList.get(position);
                                            } else {
                                                genusName = null;
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 重置筛选的数据
     */
    public void resetFiltAdapteData() {

        if (filteClassAdapter != null) {
            filteClassAdapter.resetData();
        }
        if (filteKmAdapter != null) {
            filteKmAdapter.resetData();
        }
        if (filteLevelAdapter != null) {
            filteLevelAdapter.resetData();
        }
        if (filteGenusAdapter != null) {
            filteGenusAdapter.resetData();
        }

        kmName = null;
        levelName = null;
        genusName = null;
        classType = null;


    }

    public void setOnClickListener(OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }

    public static interface OnClickListener {

        void onClickCancel();

        void onClickReset(String kmName, String classType, String levelName, String genusName);

        void onClickSure(String kmName, String classType, String levelName, String genusName);
    }
}
